import requests
from config import Config

class MultiModelChatbot:
    @staticmethod
    def get_response(user_message, conversation_history=None, model="chatgpt"):
        """
        根据前端传递的模型参数调用不同的API获取聊天回复
        """
        if conversation_history is None:
            conversation_history = []

        # 获取选择的模型的API URL和密钥
        api_url = Config.API_URLS.get(model)
        api_key = Config.API_KEYS.get(model)
        model_name = Config.MODEL_NAMES.get(model)

        # 如果找不到对应的模型配置，返回错误消息
        if not api_url or not api_key or not model_name:
            return "未知的模型类型"

        # 构建请求头和数据
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {api_key}"
        }
        messages = conversation_history + [{"role": "user", "content": user_message}]
        data = {
            "model": model_name,
            "messages": messages,
            "max_tokens": Config.MAX_TOKENS,
            "temperature": Config.TEMPERATURE
        }

        # 发起请求并返回响应
        try:
            response = requests.post(api_url, headers=headers, json=data)
            response.raise_for_status()
            result = response.json()
            return result["choices"][0]["message"]["content"]
        except requests.exceptions.RequestException as e:
            return f"抱歉，服务请求失败: {e}"
